package com.yinhe.music.yhmusic.personal;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.umeng.analytics.MobclickAgent;
import com.yinhe.music.common.GlideHelper.GlideHelper;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.application.MusicApplication;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceActivity;
import com.yinhe.music.yhmusic.cache.CacheManager;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.constants.KeyConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.login.LoginRegisterActivity;
import com.yinhe.music.yhmusic.model.LoginInfo;
import com.yinhe.music.yhmusic.model.UserInfo;
import com.yinhe.music.yhmusic.personal.feedback.FeedBackActivity;
import com.yinhe.music.yhmusic.personal.modify.ModifyActivity;
import com.yinhe.music.yhmusic.personal.vip.MyVipActivity;
import com.yinhe.music.yhmusic.utils.DataCleanManager;
import com.yinhe.music.yhmusic.utils.PlayingCoverLoader;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.UmengEventUtils;
import com.yinhe.music.yhmusic.utils.ViewUtils;

import java.util.stream.Stream;

/**
 * @author Johnson
 * @date 2018/1/23
 */

public class PersonActivity extends BaseServiceActivity implements View.OnClickListener, PersonContract.IPersonView {


    private ImageView mHeadView;
    private TextView mNameView;
    private TextView mCacheView;

    private TextView mEditView;
    private TextView mLoginView;

    private SwitchCompat mTipSwitch;

    private TextView mVipText;

    PersonPresenter<BaseModel, PersonContract.IPersonView> mPresenter;

    @Override
    public void initView() {
        RxBus.get().register(this);

        mHeadView = findViewById(R.id.head_view);
        mNameView = findViewById(R.id.name_view);
        mCacheView = findViewById(R.id.cache_view);
        mTipSwitch = findViewById(R.id.tip_switch_view);
        mEditView = findViewById(R.id.edit_view);
        mLoginView = findViewById(R.id.login_view);
        mVipText = findViewById(R.id.vip_text);

        findViewById(R.id.edit_view).setOnClickListener(this);
        findViewById(R.id.vip_layout).setOnClickListener(this);
        findViewById(R.id.my_icon_layout).setOnClickListener(this);
        findViewById(R.id.feedback_layout).setOnClickListener(this);
        findViewById(R.id.delete_layout).setOnClickListener(this);
        findViewById(R.id.about_layout).setOnClickListener(this);
        findViewById(R.id.logout_layout).setOnClickListener(this);
        mLoginView.setOnClickListener(this);

        setToolbar("个人");
        initData();
        showQuickControl(true);
    }

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(this);
        super.onDestroy();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.person_activity;
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new PersonPresenter<>();
        mPresenter.attachModelView(new BaseModel(), this);
    }

    private void initData() {
        try {
            mCacheView.setText(DataCleanManager.getTotalCacheSize(this));
        } catch (Exception e) {
            LogUtils.e(e);
        }

        mTipSwitch.setChecked(Preferences.getIsProtect());
        mTipSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            MobclickAgent.onEvent(PersonActivity.this, "network_protect");
            Preferences.setIsProtect(isChecked);
        });

        String sn = Preferences.getLoginSn();

        if (sn.isEmpty()) {
            logout();
            setLogoutUI();
            return;
        }

        setLoginUI();

        UserInfo userInfo = CacheManager.getInstance().getUserInfo();

        if (userInfo != null) {
            updateUserInfo(userInfo);
        }

        mPresenter.getUserInfo();

    }

    private void updateUserInfo(UserInfo dataBean) {
        GlideHelper.setCircleImageResource(mHeadView, dataBean.getImage(), R.drawable.default_user_head);
        Preferences.setUserImage(dataBean.getImage());
        if (dataBean.getNickname() != null) {
            mNameView.setText(dataBean.getNickname());
        } else {
            mNameView.setText(" ");
        }

        if (dataBean.getVipLevel() == 0) {
            mVipText.setText("升级为VIP");
        } else {
            mVipText.setText("VIP续费");
            Drawable drawable = getResources().getDrawable(R.drawable.icon_person_vip);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mNameView.setCompoundDrawables(null, null, drawable, null);
        }
    }

    private void setLogoutUI() {
        mNameView.setVisibility(View.GONE);
        mLoginView.setVisibility(View.VISIBLE);
        mEditView.setVisibility(View.GONE);
        mHeadView.setImageResource(R.drawable.default_user_head);
        findViewById(R.id.logout_layout).setVisibility(View.GONE);
    }

    private void setLoginUI() {
        mNameView.setVisibility(View.VISIBLE);
        mLoginView.setVisibility(View.GONE);
        mEditView.setVisibility(View.VISIBLE);

        findViewById(R.id.logout_layout).setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.edit_view:
                gotoMyInfo();
                break;
            case R.id.vip_layout:
                gotoVip();
                break;
            case R.id.my_icon_layout:
                gotoMyWallet();
                break;
            case R.id.feedback_layout:
                gotoFeedback();
                break;
            case R.id.delete_layout:
                clearCache();
                break;
            case R.id.about_layout:
                gotoAbout();
                break;
            case R.id.logout_layout:
                showExitDialog();
                break;
            case R.id.login_view:
                login();
                break;
            default:
                break;
        }
    }

    private void showExitDialog() {
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage("你确定要退出登录");
        dialog.setPositiveButton("确定", (dialogInterface, i) -> logout());
        dialog.setNegativeButton("取消", null);
        dialog.show();
    }

    private void login() {
        Intent intent = new Intent(this, LoginRegisterActivity.class);
        startActivity(intent);
    }

    private void logout() {
        UmengEventUtils.clickLogout(this);
        Preferences.setFavMenu(0);
        Preferences.setLoginSN("");
        Preferences.setIsVip(false);
        DataBaseAccessor.getInstance().uninit();
        DataBaseAccessor.getInstance().initDBHelper(MusicApplication.getInstance(), "visitor.db");
        MobclickAgent.onProfileSignOff();
        RxBus.get().post(RxBusEventType.User.LOGOUT, RxbusNullObject.INSTANCE);
        setLogoutUI();
    }

    private void gotoFeedback() {
        startActivity(new Intent(this, FeedBackActivity.class));
    }

    private void gotoAbout() {
        startActivity(new Intent(this, AboutActivity.class));
    }

    private void gotoMyInfo() {
        UserInfo userInfo = CacheManager.getInstance().getUserInfo();
        Intent intent = new Intent(this, ModifyActivity.class);
        intent.putExtra(KeyConstants.KEY_IMAGE, userInfo.getImage());
        intent.putExtra(KeyConstants.KEY_GENDER, userInfo.getGender());
        intent.putExtra(KeyConstants.KEY_NAME, userInfo.getNickname());
        intent.putExtra(KeyConstants.KEY_MODIFY_TYPE, IConstants.MODIFY_USER_INFO);
        startActivity(intent);
    }

    private void gotoVip() {
        if (!Preferences.getLoginSn().isEmpty()) {
            startActivity(new Intent(this, MyVipActivity.class));
        } else {
            startLogin();
        }

    }

    private void gotoMyWallet() {
        if (!Preferences.getLoginSn().isEmpty()) {
            startActivity(new Intent(this, MyWalletActivity.class));
        } else {
            startActivity(new Intent(this, LoginRegisterActivity.class));
        }
    }

    private void clearCache() {
        MobclickAgent.onEvent(this, "clear_cache");
        ProgressDialog dialog = ViewUtils.showWaitingDialog(this, "正在清理缓存，请稍等", null, false);
        dialog.show();
        try {
            PlayingCoverLoader.getInstance().clearCache();
            DataCleanManager.clearAllCache(this);
            mCacheView.setText(DataCleanManager.getTotalCacheSize(this));
            dialog.dismiss();
            Toast.makeText(this, "清理缓存成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            LogUtils.e(e);
        }
        mHandler.postDelayed(dialog::dismiss, 1500);
    }

    @Override
    public void setUserUI(UserInfo userInfo) {
        CacheManager.getInstance().setUserInfo(userInfo);
        RxBus.get().post(RxBusEventType.User.LOGIN_GET_USER,RxbusNullObject.INSTANCE);
        updateUserInfo(userInfo);
    }

    @Override
    public void showMessage(Throwable throwable) {
        super.showMessage(throwable);
        logout();
        setLogoutUI();
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.User.LOGIN_SUCCESS),
                    @Tag(RxBusEventType.User.REGISTER_SUCCESS)}
    )
    public void onRxbusLoginEvent(LoginInfo info) {
        initData();
    }

    @Subscribe(tags = @Tag(RxBusEventType.Music.CLOSE_NET_PROTECT))
    public void onRxbusPlayingProtect(Boolean isProtect) {
        if (mTipSwitch != null) {
            mTipSwitch.setChecked(isProtect);
        }
    }

    @Subscribe(tags = @Tag(RxBusEventType.User.UPDATE_USER_INFO))
    public void onRxbusUpdateUser(RxbusNullObject rxbusNullObject) {
        initData();
    }

}
